<?php
/**
  * Mar 5, 2008
  *
  * Coded by: Ropu
  *
  */

class HackathonDAO {
  
  public static function get(Hackathon &$hackathon) {
    $db = DB::getDB();
    $sql = "SELECT id, location, date, info FROM hackathon WHERE id = ?";
    if($stmt = $db->prepare($sql)) {
      $stmt->bind_param("i", $hackathon->getId());
      $stmt->bind_result($id, $location, $date, $info);
      $stmt->execute();
      if(!$stmt->fetch()) {
        $stmt->close();
        throw new DBException('Invalid hackathon with id: ' . $hackathon->getId());
      }
      if(Log::medium($stmt->error)) {
        $error = $stmt->error;
        $stmt->close();
        throw new DBException($error);
      }
      $hackathon->setLocation($location);
      $hackathon->setDate($date);
      $hackathon->setInfo($info);
      $stmt->close();
    }
    return $id;
  }

  public static function getByHackathon($hackathon_id) {
    $db = DB::getDB();
    $hackers = array();
    $hackers_ids = array();
    /*
     * TODO: add filter by network
     */
    $sql = "SELECT id FROM hacker 
            WHERE hackathon_id = ?";
    if($stmt = $db->prepare($sql)) {
      $stmt->bind_param("i", $hackathon_id);
      $stmt->bind_result($id);
      $stmt->execute();
      
      while($stmt->fetch()) {
        $hackers_ids[] = $id;
      }
      if(Log::medium($stmt->error)) {
        $error = $stmt->error;
        $stmt->close();
        throw new Exception($error);
      }
      $stmt->close();
      foreach($hackers_ids as $id) {
        $hackers[$id] = new Hacker($id);
      }
    }
    return $hackers;
  }
  
  public static function getList() {
    $db = DB::getDB();
    $hackathons = array();
    $hackathons_ids = array();
    $sql = "SELECT id FROM hackathon order by date desc";
    if($stmt = $db->prepare($sql)) {
      $stmt->bind_result($id);
      $stmt->execute();
      
      while($stmt->fetch()) {
        $hackathons_ids[] = $id;
      }
      if(Log::medium($stmt->error)) {
        $error = $stmt->error;
        $stmt->close();
        throw new Exception($error);
      }
      $stmt->close();
      foreach($hackathons_ids as $id) {
        $hackathons[$id] = new Hackathon($id);
      }
    }
    return $hackathons;
  }
  
}